﻿using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using Domain.Dummies;
using Domain.Dummies.Dtos;
using Domain.Dummies.Dtos.Collections;

namespace Services.Dummies.LibraryService
{
    public class DummyLibraryService : ILibraryService
    {
        public Guid CreateBookRecord(SessionDto session,  NameValueCollection attributes)
        {
            return Guid.NewGuid();
        }

        public bool UpdateBookRecord(SessionDto session,  Guid bookId, NameValueCollection attributes)
        {
            return true;
        }



        public BooksListDto GetBooksGotByPerson(SessionDto session,  Guid PersonGuid)
        {            
            BooksListDto booklist = new BooksListDto();
            booklist.HolderPersonGuid = PersonGuid;

            var query = Database.get().WhoGetBook.Where(who => who.HolderPerson.Id.Equals(PersonGuid));
            if (query.Count() != 0)
                booklist.Books = query.First().Books;
            else
                booklist.Books = new List<BookDto>();

            return booklist;
        }

        public BooksBaseListDto GetBookRecord(SessionDto session,  BookDto book)
        {
            List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>();
            BooksBaseListDto target = new BooksBaseListDto();

            foreach (System.Reflection.PropertyInfo prop in book.GetType().GetProperties())
            {
                Object value = prop.GetValue(book, null);

                if ((value == null) ||
                    (value is System.Guid && value.Equals(System.Guid.Empty)) ||
                    (value is System.Int32 && value.Equals(0))
                   ) continue;


                info.Add(prop);
            }


            IEnumerable<BookDto> query = Database.get().Books.Where(
                delegate(BookDto mybook)
                {
                    bool result = true;

                    foreach (var prop in info)
                    {
                        Object value = prop.GetValue(book, null);
                        if (value is String)
                            result &= (prop.GetValue(mybook, null) as String).ToUpper().IndexOf((value as String).ToUpper()) >= 0;
                        else
                            result &= prop.GetValue(mybook, null).Equals(value);
                    }

                    return result;
                });

            if (query.Count() > 0)
                target.Books = query.ToList();
            else
                target.Books = new List<BookDto>();

            return target;
        }
    }
}
